package com.tran.app.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tran.app.MyApp
import com.tran.app.dao.AppDatabase
import com.tran.app.data.PlainData
import com.tran.app.utils.show
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class PlainViewModel:ViewModel() {

        var data = MutableStateFlow(
                PlainData(
                        desplace = "",
                        starttime = "",
                        backtime = "",
                        money = "",
                        plain = ""
                )
        )
        var id: Int = -1

        fun updateId(newid: Int?) {
                if (newid == null) {
                        return
                }
                if (newid == -1) {
                        return
                } else {
                        id = newid
                        viewModelScope.launch {
                              AppDatabase.getInstance(MyApp.instance).
                                plainDataDao().getPlainDataById(id).collect(){
                                      data.value = it
                              }

                        }
                }
        }

        fun save(){
                viewModelScope.launch {
                        withContext(Dispatchers.IO){
                                if(id==-1){
                                        AppDatabase.getInstance(MyApp.instance).plainDataDao().insertPlainData(data.value)
                                }else{
                                        AppDatabase.getInstance(MyApp.instance).plainDataDao().updatePlainData(data.value)
                                }

                        }
                        withContext(Dispatchers.Main){
                                show("保存成功")
                        }
                }
        }

}